<?php
namespace app\erp\model;

use think\Model;
use traits\model\SoftDelete;
use app\erp\validate\Attrrule;
use think\Cache;

class Attrdb extends Model
{
    // 使用软删除
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    protected $pk = 'attr_id';

    protected $name = 'attr';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d',
        'delete_time' => 'timestamp:Y-m-d'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;
    
    // 自动完成
    protected $insert = [
        'is_must',
        'value_item',
        'site_id',
        'admin_id' => MEMBER_ID,
        'attr_sign',
        'sort'
    ];

    protected function setSiteIdAttr($value)
    {
        if (! $value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        return $value;
    }
    // 自动完成唯一标识
    protected function setAttrSignAttr($value)
    {
        if ($value) {
            return $value;
        }
        return md5(time() . round(1000, 9999));
    }
    // 自动完成是否必填
    protected function setIsMustAttr($value)
    {
        if ($value == 1) {
            return 1;
        } else {
            return 2;
        }
    }
    // 自动完成可选数值
    protected function setValueItemAttr($value)
    {
        return str_replace('，', ',', $value);
    }
    // 自动完成排序
    protected function setSortAttr()
    {
        $max_sort = $this->ajaxSortMax();
        return $max_sort + 1;
    }

    public $param = array();
    public $lastInsSign = '';

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }
    // 查询分类
    public function scopeCategorySign($query)
    {
        if ($this->param['category_sign'] != '0') {
            $query->where('category_sign', 'IN', $this->param['category_sign']);
        } else {
            $query->where('category_sign', 0);
            $query->where('admin_id', MEMBER_ID);
        }
    }

    public function scopeAttrName($query, $attr_name)
    {
        $query->where('attr_name', $attr_name);
    }
    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        if (isset($this->param['site_id'])) {
            if ($this->param['site_id'] == 0 || $this->param['site_id'] == '') {
                $query->where('site_id', 'null');
            } else {
                $query->where('site_id', $this->param['site_id']);
            }
        } else {
            if (! empty(SITE_ID)) {
                $query->where('site_id', SITE_ID);
            } else {
                $query->where('site_id', 'null');
            }
        }
        if (isset($this->param['category_sign'])) {
            $query->categorySign();
        }
        if (isset($this->param['attr_name']) && $this->param['attr_name']) {
            $query->attrName($this->param['attr_name']);
        }
        if(isset($this->param['group_name']) && $this->param['group_name']){
        	$query->groupName($this->param['group_name']);
        }
        if(isset($this->param['jd_name']) && $this->param['jd_name']){
        	$query->jdName($this->param['jd_name']);
        }
    }
    public function scopeGroupName($query,$group_name){
    	$query->where('group_name',$group_name);
    }
    public function scopeJdName($query,$jd_name){
    	$query->where('jd_name',$jd_name);
    }
    // 查询排序最大值
    public function ajaxSortMax()
    {
        $max_sort = $this->cache($this->cache_name('attr_max'), 86400, 'attr')
            ->max('sort');
        return $max_sort;
    }
    // 同步分类属性
    public function copy()
    {
        $data = $this->cache($this->cache_name('attr_select'), 86400, 'attr')
            ->select();
        if ($data) {
            $data = $data->toArray();
        }
        $add_data = array();
        if ($this->param['select_site_id'] == '') {
            $this->param['site_id'] = SITE_ID;
        } else {
            $this->param['site_id'] = $this->param['select_site_id'];
        }
        foreach ($data as $key => $val) {
            unset($val['attr_id']);
            unset($val['create_time']);
            unset($val['admin_id']);
            $val['site_id'] = $this->param['site_id'];
            $add_data[$key] = $val;
        }
        
        $this->ajaxDelete();
        $this->saveAll($add_data);
        return 'success';
    }
    // 查询列表
    public function ajaxSelect()
    {
        $return['data'] = $this->ajaxList();
        $return['count'] = $this->ajaxCount();
        return $return;
    }

    public function ajaxList()
    {
        $data = $this->cache($this->cache_name('attr_list'), 86400, 'attr')
            ->order('sort asc,group_name asc,attr_id asc')
            ->select();
        if (! $data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
        }
        return $data;
    }

    public function ajaxCount()
    {
        return $this->cache($this->cache_name('attr_count'), 86400, 'attr')
            ->count();
    }

    public function ajaxFind($attr_id)
    {
        $data = $this->useGlobalScope(false)
            ->master()
            ->where('attr_id', $this->param['attr_id'])
            ->find();
        if ($data) {
            $data = $data->toArray();
            $data = $this->handleData($data);
        } else {
            return $data;
        }
        return $data;
    }

    public function ajaxChkFind()
    {
        $data = $this->find();
        if ($data) {
            return $data->toArray();
        } else {
            return array();
        }
    }
    // 设置新增分类下的属性
    public function addCategoryAttr($category_sign)
    {
        $this->save([
            'category_sign' => $category_sign
        ], [
            'admin_id' => session('member_id'),
            'category_sign' => '0'
        ]);
        Cache::clear('attr');
    }
    // 保存数据
    public function ajaxSave()
    {
        $rule = new Attrrule();
        if (isset($this->param['attr_id']) && $this->param['attr_id'] != '') {
            if (! $rule->scene('edit')->check($this->param)) {
                return $rule->getError();
            }
            $attr_id = $this->param['attr_id'];
            unset($this->param['attr_id']);
            $this->save($this->param, [
                'attr_id' => $attr_id
            ]);
            $get_attr = $this->where('attr_id',$attr_id)->find()->toArray();
            $this->lastInsSign = $get_attr['attr_sign'];
        } else {
            if (! $rule->check($this->param)) {
                if(isset($this->param['is_update']) && $this->param['is_update'] == 'yes') {
                    $get_attr = $this->useGlobalScope(false)->where('category_sign',$this->param['category_sign'])->where('attr_name',$this->param['attr_name'])->find();
                    if($get_attr) {
                        $get_attr = $get_attr->toArray();
                        $this->lastInsSign = $get_attr['attr_sign'];
                        $this->where('attr_id', $get_attr['attr_id'])->update(['value_item' => $this->param['value_item'],'group_name'=>$this->param['group_names']]);
                        return '更新';
                    }
                } else {
                    return $rule->getError();
                }
            }
            $this->param['attr_sign'] = md5(time() . round(1000, 9999) . uniqid());
            $this->param['jd_name'] = $this->param['attr_name'];
            $this->allowField(true)->save($this->param);
           // halt($this->getLastSql());
            $this->lastInsSign = $this->data['attr_sign'];
        }

        Cache::clear('attr');
        return 'success';
    }
    // 软删除
    public function ajaxDelete()
    {
        if (isset($this->param['attr_id'])) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('attr_id', 'IN', $this->param['attr_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('attr_id', 'IN', $this->param['attr_id']);
                }, true);
            }
        }
        if (isset($this->param['category_sign'])) {
            $this->where('site_id', $this->param['site_id'])->delete();
        }
        Cache::clear('attr');
        return 'success';
    }
    // 数据处理
    protected function handleData($val)
    {
        $sitedb = new Sitedb();
        foreach ($val as $k => $v) {
            $val[$k] = $v;
            switch ($k) {
                case 'value_item':
                    $val[$k] = explode(',', str_replace('"','“',$v));
                    break;
                default:
                    break;
            }
        }
        return $val;
    }
}